package cn.achao.csr.openapi.core.utils;

import cn.achao.csr.api.model.entity.RestBean;
import cn.achao.csr.api.model.entity.SysApi;
import cn.achao.csr.api.model.enums.BodyTypeEnums;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

/**
 * @Author: achao
 **/
public class HttpResUtils {

    public static RestBean get(HttpMethod method, SysApi api) {
        String address = api.getAddress();
        HttpHeaders httpHeaders = getHttpHeaders(api.getHeaderInfo());
        int timeout = Optional.ofNullable(api.getTimeout()).orElse(5000);
        RestTemplate restTemplate = RestUtils.getRestTemplate(timeout);
        ResponseEntity<String> exchange = RestUtils.exchange(restTemplate, httpHeaders, address, method, "");
        return RestUtils.getRestBean(exchange);
    }

    public static RestBean post(HttpMethod method, SysApi httpIntfConf, String json) {

        String address = httpIntfConf.getAddress();
        HttpHeaders httpHeaders = getHttpHeaders(httpIntfConf.getHeaderInfo());
        int timeout = Optional.ofNullable(httpIntfConf.getTimeout()).orElse(5000);
        RestTemplate restTemplate = RestUtils.getRestTemplate(timeout);
        ResponseEntity<String> exchange = RestUtils.exchange(restTemplate, httpHeaders, address, method, json);
        return RestUtils.getRestBean(exchange);
    }

    public static HttpHeaders getHttpHeaders(String headerInfo) {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (StringUtils.isNotBlank(headerInfo)) {
            JSONObject jsonObject = JSONUtil.parseObj(headerInfo);
            if (!jsonObject.isEmpty()) {
                jsonObject.forEach((k, v) -> {
                    v = ObjectUtil.isEmpty(v) ? "" : v;
                    httpHeaders.set(k, (String) v);
                });
            }
        }
        return httpHeaders;
    }


}
